package org.minuframework.file;

import java.io.File;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.RequestContext;
import org.minuframework.lang.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

public abstract class FileUploaderBase {
    
    public static final String FORM_DATA = "form-data";
    
    public static final String MULTIPART = "multipart/";
    
    public static final String MULTIPART_FORM_DATA = "multipart/form-data";
    
    public static final String MULTIPART_MIXED = "multipart/mixed";
    
    protected HttpServletRequest request;
    
    /**
     * spring框架文件上传
     */
    protected MultipartFile multipartFile;
    
    /**
     * 前缀
     */
    protected String prefix;
    
    /**
     * 上传路径
     */
    protected File upload;
    
    /**
     * 目标路径
     */
    protected File target;
    
    /**
     * base64编码字符串
     */
    protected String imgstr;
    
    protected Map<String, Object> partMap;
    
    public HttpServletRequest getRequest() {
        return request;
    }
    
    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }
    
    public MultipartFile getMultipartFile() {
        return multipartFile;
    }
    
    public void setMultipartFile(MultipartFile multipartFile) {
        this.multipartFile = multipartFile;
    }
    
    public File getUpload() {
        return upload;
    }
    
    public void setUpload(File upload) {
        this.upload = upload;
    }
    
    public File getTarget() {
        return target;
    }
    
    public void setTarget(File target) {
        this.target = target;
    }
    
    public String getImgstr() {
        return imgstr;
    }
    
    public void setImgstr(String imgstr) {
        this.imgstr = imgstr;
    }
    
    public String getPrefix() {
        return prefix;
    }
    
    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }
    
    public static MultipartHttpServletRequest getMutipartHttpServletRequest(HttpServletRequest request) {
        return request instanceof MultipartHttpServletRequest ? (MultipartHttpServletRequest) request : new DefaultMultipartHttpServletRequest(
                request);
    }
    
    public static boolean isMultipartContent(RequestContext context) {
        String contentType = context.getContentType();
        if (StringUtils.isEmpty(contentType)) { return false; }
        return contentType.toLowerCase(Locale.ENGLISH).startsWith(MULTIPART);
    }
    
}
